﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Cherry.Agile.Framework;
using Cherry.Agile.Security;
using Cherry.Agile.UI.Framework.Configuration;
using System.Data;

namespace Cherry.Agile.UI.Framework
{
    /// <summary>
    /// 
    /// </summary>
    public static class Unity
    {
        public const string APP_KEY = "D1785896856AC";

        public static string AsCookieKey(this string val)
        {
            return string.Format("{0}_{1}", val, ApplicationContext.InstanseId);
        }

        ///// <summary>
        ///// 重定向
        ///// </summary>
        ///// <param name="page"><see cref="Page"/></param>
        ///// <param name="appId">重定向的业务系统编号，默认是当前系统</param>
        ///// <param name="url">重定向Url</param>
        //public static void Redirect(this Page page, string url, int appId = 0)
        //{
        //    url = MemberManager.ResolveUrl(url);
        //    page.Response.Redirect(url);
        //}

        ///// <summary>
        ///// 获取Url对应的绝对路径
        ///// </summary>
        ///// <param name="url">相对URL</param>
        ///// <param name="appId">业务系统编号，默认是当前系统</param>
        ///// <param name="page"><see cref="Page"/></param>
        ///// <returns>绝对URL</returns>
        //public static string Url(this Page page, string url, int appId = 0)
        //{
        //    return MemberManager.ResolveUrl(page.ResolveUrl(url));
        //}

        public static string AsResourceUrl(this string url)
        {
            return ApplicationContext.ResouceUrlRoot + url;
        }

        /// <summary>
        /// 让服务器按钮点击后变灰
        /// </summary>
        /// <param name="button"></param>
        /// <param name="newText">点后的显示文本</param>
        public static void ClickDisabled(this System.Web.UI.WebControls.Button button, string newText = "")
        {
            if (button == null) return;
            StringBuilder js = new StringBuilder();
            System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;
            page.ClientScript.GetPostBackEventReference(button, string.Empty);

            if (!button.ValidationGroup.IsNullOrEmpty())
            {
                js.AppendFormat("if({0})", button.ValidationGroup);
                js.Append("{");
                if (!button.OnClientClick.IsNullOrEmpty())
                {
                    js.Append(button.OnClientClick);
                }
                js.Append("this.disabled=true;");
                if (!newText.IsNullOrEmpty())
                {
                    js.AppendFormat("this.value=\"{0}\";", newText);
                }
                js.AppendFormat("__doPostBack(\"{0}\",\"\");", button.ID);
                js.Append("}else{return false;}");
            }
            else
            {
                if (!button.OnClientClick.IsNullOrEmpty())
                {
                    js.Append(button.OnClientClick);
                }
                js.Append("this.disabled=true;");
                if (!newText.IsNullOrEmpty())
                {
                    js.AppendFormat("this.value=\"{0}\";", newText);
                }
                js.AppendFormat("__doPostBack(\"{0}\",\"\");", button.ID);
            }
            button.OnClientClick = js.ToString();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string UrlDecode(this string val)
        {
            if (string.IsNullOrEmpty(val))
                return val;
            return HttpUtility.UrlDecode(val);
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientIP(this HttpContext context)
        {
            var request = context.Request;
            string userIP = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (userIP == null || userIP == "")
            {
                userIP = request.ServerVariables["REMOTE_ADDR"];
            }
            return userIP;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string UrlEncode(this string val)
        {
            if (string.IsNullOrEmpty(val))
                return val;
            return HttpUtility.UrlEncode(val);
        }

        /// <summary>
        /// 得到用户浏览器类型
        /// </summary>
        /// <returns></returns>
        public static string GetBrowse()
        {
            return System.Web.HttpContext.Current.Request.Browser.Type;
        }

        /// <summary>
        /// 获取浏览器端操作系统名称
        /// </summary>
        /// <returns></returns>
        public static string GetOSName()
        {
            string osVersion = System.Web.HttpContext.Current.Request.Browser.Platform;
            string userAgent = System.Web.HttpContext.Current.Request.UserAgent;

            if (userAgent.Contains("NT 6.3"))
            {
                osVersion = "Windows8.1";
            }
            else if (userAgent.Contains("NT 6.2"))
            {
                osVersion = "Windows8";
            }
            else if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows7";
            }
            else if (userAgent.Contains("NT 6.0"))
            {
                osVersion = "WindowsVista";
            }
            else if (userAgent.Contains("NT 5.2"))
            {
                osVersion = "WindowsServer2003";
            }
            else if (userAgent.Contains("NT 5.1"))
            {
                osVersion = "WindowsXP";
            }
            else if (userAgent.Contains("NT 5"))
            {
                osVersion = "Windows2000";
            }
            else if (userAgent.Contains("NT 4"))
            {
                osVersion = "WindowsNT4.0";
            }
            else if (userAgent.Contains("Me"))
            {
                osVersion = "WindowsMe";
            }
            else if (userAgent.Contains("98"))
            {
                osVersion = "Windows98";
            }
            else if (userAgent.Contains("95"))
            {
                osVersion = "Windows95";
            }
            else if (userAgent.Contains("Mac"))
            {
                osVersion = "Mac";
            }
            else if (userAgent.Contains("Unix"))
            {
                osVersion = "UNIX";
            }
            else if (userAgent.Contains("Linux"))
            {
                osVersion = "Linux";
            }
            else if (userAgent.Contains("SunOS"))
            {
                osVersion = "SunOS";
            }
            return osVersion;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string val)
        {
            return HttpUtility.HtmlEncode(val);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string val)
        {
            return HttpUtility.HtmlDecode(val);
        }

        public static HttpCookie CrossDomain(this HttpCookie cookie)
        {
            cookie.Domain = FormsAuthentication.CookieDomain;
            return cookie;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string CreateSign(IDictionary<string, string> parameters, string secret)
        {

            //md5:将secretcode同时拼接到参数字符串头、尾部进行md5加密，再转化成大写，格式是：uppercase(md5(secretkey1value1key2value2...secret)。
            //例如:uppercase(md5（secretbar2baz3foo1secret)) 

            parameters.Remove("sign");

            //第一步：把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            //第二步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder(secret);
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append(value);
                }
            }
            query.Append(secret);// API 2.0 新签名方法            

            return query.ToString().MD5().ToUpper();
        }

        /// <summary>
        /// SignUrl
        /// </summary>
        /// <param name="vals">
        /// key1,val1,key2,val2....
        /// </param>
        /// <returns></returns>
        public static string SignUrl(params string[] vals)
        {
            var ps = new SortedDictionary<string, string>();
            if (vals.Length <= 1 || vals.Length % 2 != 0)
                throw new ArgumentException("vals length must be more than two.");

            for (int i = 0; i < vals.Length - 2; i += 2)
            {
                ps.Add(vals[i], vals[i + 1]);
            }
            var expect = Cherry.Agile.UI.Framework.Unity.CreateSign(ps, APP_KEY);
            return expect;
        }

        public static void CrossRedirect(this HttpResponse response, string url, string site = null)
        {
            var user = System.Threading.Thread.CurrentPrincipal.Identity as User;
            if (user == null)
                throw new ArgumentNullException("current user is null");
            var type = user.UserType.ToString();
            var account = user.Identity;
            var p = user.Password;
            var returnUrl = url.UrlEncode();
            var time = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");

            var sign = SignUrl("account", account, "p", p, "returnurl", returnUrl, "time", time, "type", type);

            if (string.IsNullOrEmpty(site))
                site = AgileWebSection.Instance.SSO.PassportSite;
            if (site == null)
                throw new ArgumentNullException("the passport site value can not be null.");

            var val = site.Trim('/') + "/proxy.aspx?" +
                string.Format("account={0}&p={1}&type={2}&time={3}&returnurl={4}&sign={5}", account, p, type, time, returnUrl, sign);

            response.Redirect(val, true);
        }

//        /// <summary>
//        /// 导出数据到EXCEL
//        /// </summary>
//        /// <param name="dataTable">数据的表格格式</param>
//        /// <param name="fileName">导出文件的名称</param>
//        /// <param name="page">调用的页面</param>
//        public static void ExportToExcelFormat(DataTable dataTable, string fileName, Page page)
//        {

//            HtmlGenericControl html = new HtmlGenericControl("html");
//            HtmlGenericControl body = new HtmlGenericControl("body")
//            {
//                InnerHtml = @"<!--[if gte mso 9]><xml>
// <x:ExcelWorkbook>
//  <x:ExcelWorksheets>
//   <x:ExcelWorksheet>
//    <x:Name>Sheet1</x:Name>
//    <x:WorksheetOptions>
//     <x:DefaultRowHeight>285</x:DefaultRowHeight>
//     <x:Selected/>
//     <x:Panes>
//      <x:Pane>
//       <x:Number>3</x:Number>
//       <x:ActiveRow>3</x:ActiveRow>
//       <x:ActiveCol>2</x:ActiveCol>
//      </x:Pane>
//     </x:Panes>
//     <x:ProtectContents>False</x:ProtectContents>
//     <x:ProtectObjects>False</x:ProtectObjects>
//     <x:ProtectScenarios>False</x:ProtectScenarios>
//    </x:WorksheetOptions>
//   </x:ExcelWorksheet>
//   <x:ExcelWorksheet>
//    <x:Name>Sheet2</x:Name>
//    <x:WorksheetOptions>
//     <x:DefaultRowHeight>285</x:DefaultRowHeight>
//     <x:ProtectContents>False</x:ProtectContents>
//     <x:ProtectObjects>False</x:ProtectObjects>
//     <x:ProtectScenarios>False</x:ProtectScenarios>
//    </x:WorksheetOptions>
//   </x:ExcelWorksheet>
//   <x:ExcelWorksheet>
//    <x:Name>Sheet3</x:Name>
//    <x:WorksheetOptions>
//     <x:DefaultRowHeight>285</x:DefaultRowHeight>
//     <x:ProtectContents>False</x:ProtectContents>
//     <x:ProtectObjects>False</x:ProtectObjects>
//     <x:ProtectScenarios>False</x:ProtectScenarios>
//    </x:WorksheetOptions>
//   </x:ExcelWorksheet>
//  </x:ExcelWorksheets>
//  <x:WindowHeight>9600</x:WindowHeight>
//  <x:WindowWidth>15075</x:WindowWidth>
//  <x:WindowTopX>480</x:WindowTopX>
//  <x:WindowTopY>90</x:WindowTopY>
//  <x:ProtectStructure>False</x:ProtectStructure>
//  <x:ProtectWindows>False</x:ProtectWindows>
// </x:ExcelWorkbook>
//</xml><![endif]-->"
//            };
//            HtmlGenericControl head = new HtmlGenericControl("head")
//            {
//                InnerHtml = @"<style>.style0
//    {
//    font-size:9.5pt;
//    font-weight:400;
//    font-style:normal;
//    font-family:宋体;
//    mso-generic-font-family:auto;
//    mso-font-charset:134;}
//td{mso-style-parent:style0;
//    mso-number-format:""\@"";  
//}</style>"
//            };
//            HtmlTable table = new HtmlTable();

//            html.Controls.Add(head);
//            html.Controls.Add(body);
//            body.Controls.Add(table);

//            HtmlTableRow th = new HtmlTableRow();
//            table.Rows.Add(th);

//            foreach (DataColumn column in dataTable.Columns)
//            {
//                th.Cells.Add(new HtmlTableCell("th")
//                {
//                    InnerText = column.Caption
//                });
//            }

//            foreach (DataRow dr in dataTable.Rows)
//            {
//                HtmlTableRow row = new HtmlTableRow();
//                table.Rows.Add(row);
//                for (int i = 0; i < dataTable.Columns.Count; i++)
//                {
//                    HtmlTableCell cell = new HtmlTableCell()
//                    {
//                        InnerText = dr[i].ToString()
//                    };
//                    //cell.Attributes["class"] = "xlsText borders";

//                    row.Controls.Add(cell);
//                }
//            }

//            HttpResponse resp;
//            resp = page.Response;
//            resp.ContentEncoding = System.Text.Encoding.Default;
//            resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
//            System.IO.StringWriter sw = new System.IO.StringWriter();
//            Html32TextWriter hw = new Html32TextWriter(sw);
//            html.RenderControl(new Html32TextWriter(sw));
//            resp.Write(sw.ToString());
//            resp.End();
//            return;
//        }

//        /// <summary>
//        /// 导出数据到EXCEL，只导出数据。
//        /// </summary>
//        /// <param name="dataTable">数据的表格格式</param>
//        /// <param name="fileName">导出文件的名称</param>
//        /// <param name="page">调用的页面</param>
//        public static void ExportToExcel(DataTable dataTable, string fileName, Page page)
//        {
//            HttpResponse resp;
//            resp = page.Response;
//            resp.ContentEncoding = System.Text.Encoding.Default;
//            resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
//            int columnNum = dataTable.Columns.Count;
//            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符
//            string colHeadStr = "";
//            for (int i = 0; i < columnNum; i++)
//            {
//                if (i == (columnNum - 1))//最后一列，加\n
//                {
//                    colHeadStr += dataTable.Columns[i].Caption.ToString() + "\n";
//                }
//                else
//                {
//                    colHeadStr += dataTable.Columns[i].Caption.ToString() + "\t";
//                }
//            }
//            resp.Write(colHeadStr);


//            string colItemStr = "";
//            for (int i = 0; i < dataTable.Rows.Count; i++)
//            {
//                colItemStr = "";
//                for (int j = 0; j < columnNum; j++)
//                {
//                    if (j == columnNum - 1)
//                    {
//                        colItemStr = colItemStr + dataTable.Rows[i][j] + "\n";
//                    }
//                    else
//                    {
//                        colItemStr = colItemStr + dataTable.Rows[i][j] + "\t";
//                    }
//                }
//                resp.Write(colItemStr);
//            }
//            resp.End();
//        }
    }
}
